package com.atguigu.flinksql;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.$;

public class Flink09_Time_Event_sql {
    public static void main(String[] args) {
        Configuration configuration = new Configuration();
        configuration.setInteger("rest.port",10000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(configuration);
        env.setParallelism(2);

        //根据数据中的时间属性创建事件时间
        DataStream<WaterSensor> waterSensorStream =
                env
                        .fromElements(new WaterSensor("sensor_1", 1001L, 10),
                                new WaterSensor("sensor_1", 2000L, 20),
                                new WaterSensor("sensor_2", 3000L, 30),
                                new WaterSensor("sensor_1", 4000L, 40),
                                new WaterSensor("sensor_1", 5000L, 50),
                                new WaterSensor("sensor_2", 6000L, 60))
                        .assignTimestampsAndWatermarks(
                                WatermarkStrategy
                                        .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                        .withTimestampAssigner((ws, ts) -> ws.getTs())
                        );

        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);

        //将现有字段标记为事件时间
        Table table = tEnv.fromDataStream(waterSensorStream, $("id"), $("ts").rowtime(), $("vc"));

        //打印输出表中内容
        table.execute().print();



    }
}
